package com.heima.search.listen;

import com.heima.feigns.ArticleFeign;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Resource
    ArticleFeign articleFeign;
    @Resource
    ArticleSearchService articleSearchService;

    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void addArticle(String articleId) {
        log.info("搜索微服务接收到添加文章到索引库的消息==》{}", articleId);
        ResponseResult<SearchArticleVO> articleVOResult = articleFeign.findArticle(Long.valueOf(articleId));
        if (!articleVOResult.checkCode()) {
            log.error("索引库添加失败 远程调用信息失败 文章id {}", articleId);
        }
        SearchArticleVO searchArticleVO = articleVOResult.getData();
        if (searchArticleVO == null) {
            log.error("未获取到文章数据，文章id{}", articleId);
        }
        try {
            articleSearchService.saveArticle(searchArticleVO);
            log.info("成功添加索引信息add 文章id{}", articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("未成功添加文章消息add，文章id{}", articleId);
        }
    }

    //    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
//    public void removeArticle(String articleId){
//        log.info("搜索微服务接收到删除文章到索引库的消息==》{}",articleId);
//        try {
//            articleSearchService.deleteArticle(articleId);
//            log.info("成功删除索引信息 文章id{}",articleId);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("未成功删除索引信息 文章id{}",articleId);
//        }
//    }
    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void removeArticle(String articleId) {
        log.info("搜索微服务 接收到删除索引库文章消息==> {}", articleId);
        try {
            articleSearchService.deleteArticle(articleId);
            log.info("成功更新索引信息   delete: {}", articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}", articleId, e.getMessage());
        }
    }
}
